package com.gopay.common.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoadBalancingUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(LoadBalancingUtils.class);
    private static String realIpStr = "";
    
    static{
        ResourceBundle lbBundle = ResourceBundle.getBundle("loadbalancing");
        String ipsStr = lbBundle.getString("ip.infos");
        String[] ipStrArr = StringUtils.split(ipsStr,";");
        
        Map<String, String> lbMap = new HashMap<String, String>();
        
        for(String ipStr: ipStrArr){
            String key = StringUtils.split(ipStr,":")[0];
            String value = StringUtils.split(ipStr,":")[1];
            logger.info(String.format("ipStr:%s, key:%s, value:%s", ipStr, key, value));
            lbMap.put(key, value);
        }
        
        Enumeration<NetworkInterface> e = null;
        try {
            boolean isBreak = false;
            e = NetworkInterface.getNetworkInterfaces();
            while (e.hasMoreElements()) {
                if (isBreak) {
                    break;
                }
                NetworkInterface n = (NetworkInterface) e.nextElement();
                Enumeration<InetAddress> ee = n.getInetAddresses();
                while (ee.hasMoreElements()) {
                    InetAddress i = (InetAddress) ee.nextElement();
                    logger.info(String.format("枚举IP地址链: HostAddress=%s", i.getHostAddress()));
                    if (lbMap.containsKey(i.getHostAddress())) {
                        realIpStr = lbMap.get(i.getHostAddress());
                        isBreak = true;
                        break;
                    }
                }
            }
        } catch (SocketException se) {
            logger.error("识别服务器真实IP地址异常", se);
            se.printStackTrace();
        }
    }
    
    public static String getRealIp(){
        return realIpStr;
    }

}
